<template>
    <div class="ct-bodySet">
        <el-container>
            <el-header class="bgclr-dk-sp0 mb20 headerCoster" >
                <el-breadcrumb separator-class="el-icon-arrow-right">
                    <el-breadcrumb-item :to="{ path: '/mainPage/welcome' }">首页</el-breadcrumb-item>
                    <el-breadcrumb-item>看板管理</el-breadcrumb-item>
                    <el-breadcrumb-item><span class="main-Clr-ft">生成看板</span></el-breadcrumb-item>
                </el-breadcrumb>
            </el-header>
            <!--limit:最大上传数，on-exceed：超过最大上传数量时的操作  -->

            <el-card class="box-card">
                <div slot="header" class="clearfix">
                    <span>任务管理</span>
                    <el-button style="float: right; padding: 3px 0" type="text" @click="generateBoard()">生成看板文件</el-button>
                </div>
                <div style="margin-bottom: 6%">
                    <el-col :span="12">
                        <el-form :inline="false"  :model="formData" ref="formData" class="noMarginBottom" label-width="80px">
                            <el-form-item class="mb1" prop="task" label="任务">
                                <el-input  class="inputvalid" placeholder="请输入匹配任务字段" size="small" v-model.trim="formData.task"></el-input>
                            </el-form-item>
                            <el-form-item class="mb1" prop="startTime" label="开始时间">
                                <el-input class="inputvalid" placeholder="请输入匹配开始时间字段" size="small" v-model.trim="formData.startTime"></el-input>
                            </el-form-item>
                            <el-form-item class="mb1" prop="endTime" label="结束时间">
                                <el-input class="inputvalid"  placeholder="请输入匹配结束时间字段" size="small" v-model.trim="formData.endTime"></el-input>
                            </el-form-item>
                            <el-form-item class="mb1" prop="endTime" label="工时">
                                <el-input class="inputvalid" placeholder="请输入匹配工时字段" size="small" v-model.trim="formData.time"></el-input>
                            </el-form-item>
                            <el-form-item class="mb1" prop="person" label="经办人                                                                                                                                                                   ">
                                <el-input class="inputvalid" placeholder="请输入匹配经办人字段" size="small" v-model.trim="formData.person"></el-input>
                            </el-form-item>
                        </el-form>
                    </el-col>
                    <el-col :span="12">
                        <div style="margin-bottom: 6%">
                            <el-col :span="24" style="margin-right: 20%">
                                <el-upload
                                        class="upload-demo"
                                        action=""
                                        :on-change="handleChange"
                                        :on-remove="handleRemove"
                                        :on-exceed="handleExceed"
                                        :limit="1"
                                        accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"
                                        :auto-upload="false">
                                    <el-button size="small" type="primary">点击上传</el-button>
                                    <div slot="tip" class="el-upload__tip">只能上传后缀为xlsx/xlx的excel</div>
                                </el-upload>
                            </el-col>
                        </div>
                    </el-col>
                </div>
                <el-col :span="24">
                    <div><br></div>
                </el-col>
            </el-card>

        </el-container>
    </div>
</template>

<script>
    import urlConfig from '../../../config/url.json';
    import Vue from 'vue';
    import { Message } from 'element-ui';
    import XLSX from 'xlsx'
    Vue.use(XLSX);

    Vue.component(Message.name, Message);
    let generateBoardUrl = urlConfig.generateBoard;

    export default {
        data(){
            return {
                formData: {
                    task:'描述',
                    startTime:'预计开始时间',
                    endTime:'预计结束时间',
                    time:'预估工作工时(h)',
                    person:'经办人',
                    type:'问题类型'
                },
                taskArr:[],
                fileName:'',
            }
        },
        methods:{
            //生成看板
            generateBoard(){
                let that = this;
                const loading = that.$loading({
                    lock: true,
                    text: 'Loading',
                    spinner: 'el-icon-loading',
                });
                that.$http({
                    method: 'post',
                    url: generateBoardUrl,
                    baseURL: '/api',
                    data: {
                        "taskList":that.taskArr,
                        "fileName":that.fileName
                    },
                    responseType: 'blob'
                }).then(function (response) {
                    const link = document.createElement('a');
                    let blob = new Blob([response.data], {type: 'application/vnd.ms-excel'});
                    link.style.display = "none";
                    link.href = URL.createObjectURL(blob);
                    link.setAttribute('download', that.fileName);
                    document.body.appendChild(link);
                    link.click();
                    document.body.removeChild(link);
                    loading.close();
                }).catch(function (err) {
                    console.log(err);
                    Message.error('生成看板文件失败');
                    loading.close();
                });
            },
            //上传文件时处理方法
            handleChange(file, fileList){
                this.fileTemp = file.raw;
                if(this.fileTemp){
                    if((this.fileTemp.type == 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') || (this.fileTemp.type == 'application/vnd.ms-excel')){
                        this.importExcel(this.fileTemp);
                    } else {
                        this.$message({
                            type:'warning',
                            message:'附件格式错误，请删除后重新上传！'
                        });
                    }
                } else {
                    this.$message({
                        type:'warning',
                        message:'请上传附件！'
                    })
                }
            },
            //超出最大上传文件数量时的处理方法
            handleExceed(files, fileList){
                if(fileList.length>=1){
                    Message.warning("只能上传一个文件，想要再次上传，需要删除已上传文件！");
                    return;
                }
            },
            //移除文件的操作方法
            handleRemove(file,fileList){
                console.log(file, fileList);
            },
            importExcel(obj) {
                let that = this;
                that.taskArr=[];
                that.fileName='';
                debugger;
                let inputDOM = that.$refs.inputer;
                // 通过DOM取文件数据

                that.file = event.currentTarget.files[0];
                that.fileName = that.file.name;

                var rABS = false; //是否将文件读取为二进制字符串
                var f = that.file;

                var reader = new FileReader();
                //if (!FileReader.prototype.readAsBinaryString) {
                FileReader.prototype.readAsBinaryString = function(f) {
                    var binary = "";
                    var rABS = false; //是否将文件读取为二进制字符串
                    var pt = that;
                    var wb; //读取完成的数据
                    var outdata;
                    var reader = new FileReader();
                    reader.onload = function(e) {
                        var bytes = new Uint8Array(reader.result);
                        var length = bytes.byteLength;
                        for (var i = 0; i < length; i++) {
                            binary += String.fromCharCode(bytes[i]);
                        }
                        //此处引入，用于解析excel
                        var XLSX = require("xlsx");
                        if (rABS) {
                            wb = XLSX.read(btoa(fixdata(binary)), {
                                //手动转化
                                type: "base64"
                            });
                        } else {
                            wb = XLSX.read(binary, {
                                type: "binary"
                            });
                        }

                        outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);
                        //outdata就是读取的数据（不包含标题行即表头，表头会作为对象的下标）
                        //此处可对数据进行处理
                        outdata.map(v => {
                            let obj = {};
                            obj.task = "【" + v[that.formData.type] +  "】-"+ v[that.formData.task];
                            if(typeof (v[that.formData.startTime])=='number' &&(v[that.formData.startTime]).constructor==Number){
                                obj.startTime = that.formatDate(v[that.formData.startTime], ".");
                            }else{
                                obj.startTime = v[that.formData.startTime]
                            }
                            if(typeof (v[that.formData.endTime])=='number' &&(v[that.formData.endTime]).constructor==Number){
                                obj.endTime = that.formatDate(v[that.formData.endTime], ".");
                            }else{
                                obj.endTime = v[that.formData.endTime]
                            }
                            obj.time = v[that.formData.time];
                            obj.person = v[that.formData.person];
                            obj.type = v[that.formData.type];
                            that.taskArr.push(obj)
                        });
                    };
                    reader.readAsArrayBuffer(f);
                };
                if (rABS) {
                    reader.readAsArrayBuffer(f);
                } else {
                    reader.readAsBinaryString(f);
                }
            },
            formatDate(numb, format) {
                const time = new Date((numb - 1) * 24 * 3600000 + 1);
                time.setYear(time.getFullYear() - 70);
                // const year = time.getFullYear() + ''
                const month = time.getMonth() + 1 + '';
                const date = time.getDate() - 1 + '';
                if (format && format.length === 1) {
                    return   month + format + date
                }
                return year + (month < 10 ? '0' + month : month) + (date < 10 ? '0' + date : date)
            },
        },
        mounted(){
            let that = this;

        },
        updated(){
            let that=this;

        }
    }
</script>

<style scoped>
    .inputWidth{
        width: 77%;
    }

    .headerCoster{
        height: 59px;
        border-top: 1px solid #eee;
        border-bottom: 1px solid #eee;
    }

    /*计数*/
    .countNumber{
        margin-right: 23%;
    }

    .submitButton{
        margin-left: 19%;
    }

    /*.roleCardHight {*/
    /*height: 611px;*/
    /*}*/

    .cardMinWidth{
        min-width: 275px;
    }
    .inputvalid{
        width:50%;
    }

    .cardWidth{
        width: 100%;
    }
</style>